<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace LeoMQ;


use LeoMQ\Exceptions\NotFoundMQRealizeException;
use LeoMQ\Intf\ConsumerInterface;
use LeoMQ\Intf\ProducerInterface;
use Selibra\Config\Config;
use Selibra\Di\DI;
use Selibra\Di\Exception\NoImplementClass;
use Selibra\Tools\Console;

class RealizeFactory
{

    /**
     * @param string|null $key
     * @return ConsumerInterface
     * @throws NotFoundMQRealizeException
     * @throws \ReflectionException
     * @throws NoImplementClass
     */
    public static function getConsumer(string $key = null): ConsumerInterface
    {
        $key = 'consumer:' . ($key ?: self::getDefaultKey());
        return self::getRealize($key);
    }


    /**
     * @param string|null $key
     * @return ProducerInterface
     * @throws NotFoundMQRealizeException
     * @throws \ReflectionException
     * @throws NoImplementClass
     */
    public static function getProducer(string $key = null): ProducerInterface
    {
        $key = 'producer:' . ($key ?: self::getDefaultKey());
        return self::getRealize($key);
    }


    /**
     * @param string $key
     * @return mixed
     * @throws NotFoundMQRealizeException
     * @throws \ReflectionException
     * @throws NoImplementClass
     */
    private static function getRealize(string $key)
    {
        $collection = new RealizesCollection();
        $class = $collection[$key];
        if( empty($class) ){
            throw new NotFoundMQRealizeException($key, 1000);
        }
        // 实例化
        return DI::getObjectContext($class);
    }


    /**
     * @return mixed
     */
    private static function getDefaultKey()
    {
        return Config::get('LeoMQ.defaultMQ');
    }

}